using System;
using System.Collections.Generic;
using System.Linq;
using Voodoo.Sauce.Internal;

namespace Voodoo.Sauce.Core
{
	public class PurchaseDelegateList
	{
		private const string TAG = "PurchaseDelegateList";

		private readonly List<IPurchaseDelegateWithInfo> _purchaseDelegates;

		public PurchaseDelegateList()
		{
			_purchaseDelegates = new List<IPurchaseDelegateWithInfo>();
		}

		public void Add(IPurchaseDelegateWithInfo item)
		{
			if (!_purchaseDelegates.Contains(item))
			{
				_purchaseDelegates.Add(item);
			}
		}

		public void Remove(IPurchaseDelegateWithInfo item)
		{
			if (_purchaseDelegates.Contains(item))
			{
				_purchaseDelegates.Remove(item);
			}
		}

		public void OnInitializeSuccess()
		{
			foreach (IPurchaseDelegateWithInfo item in _purchaseDelegates.ToList())
			{
				try
				{
					item.OnInitializeSuccess();
				}
				catch (Exception ex)
				{
					VoodooLog.LogError(Module.IAP, "PurchaseDelegateList", ex.Message);
				}
			}
		}

		public void OnInitializeFailure(VoodooInitializationFailureReason reason)
		{
			foreach (IPurchaseDelegateWithInfo item in _purchaseDelegates.ToList())
			{
				try
				{
					item.OnInitializeFailure(reason);
				}
				catch (Exception ex)
				{
					VoodooLog.LogError(Module.IAP, "PurchaseDelegateList", ex.Message);
				}
			}
		}

		public void OnPurchaseComplete(ProductReceivedInfo productInfo, PurchaseValidation purchaseValidation, bool sendRewardEvent)
		{
			if (_purchaseDelegates.Count > 0 && sendRewardEvent)
			{
				IAPAnalytics.Reward(productInfo, purchaseValidation);
			}
			foreach (IPurchaseDelegateWithInfo item in _purchaseDelegates.ToList())
			{
				try
				{
					item.OnPurchaseComplete(productInfo, purchaseValidation);
				}
				catch (Exception ex)
				{
					VoodooLog.LogError(Module.IAP, "PurchaseDelegateList", ex.Message);
				}
			}
		}

		public void OnPurchaseFailure(VoodooPurchaseFailureReason reason, ProductReceivedInfo productInfo, string description)
		{
			foreach (IPurchaseDelegateWithInfo item in _purchaseDelegates.ToList())
			{
				try
				{
					item.OnPurchaseFailure(reason, productInfo, description);
				}
				catch (Exception ex)
				{
					VoodooLog.LogError(Module.IAP, "PurchaseDelegateList", ex.Message);
				}
			}
		}
	}
}
